<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <!--              <select-project-input v-model="model.projectId" placeholder="请选择关联项目" projectStatus="2" :signUnit="sellerUnit" :teamId="teamId" :disabled="formDisabled" @input="selectProject" />-->
              <select-project-input
                v-model="model.projectId"
                placeholder="请选择关联项目"
                projectStatus="2"
                queryParamType="2"
                :signUnit="sellerUnit"
                :teamId="teamId"
                :disabled="formDisabled"
                @input="selectProject" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectCode">
              <a-input disabled v-model="model.projectCode" placeholder="请输入项目编号" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attributionYear">
              <j-dict-select-tag disabled type="list" v-model="model.attributionYear" dictCode="yjgsnd" placeholder="请选择业绩归属年度"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
              <select-user-by-dep
                placeholder="请选择项目承接人"
                :disabled="datailDisabled"
                v-model="model.undertaker"/>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attributionYear">
              <j-dict-select-tag :disabled="datailDisabled" type="list" v-model="model.attributionYear" dictCode="yjgsnd" placeholder="请选择业绩归属年度"/>
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="12">
            <a-form-model-item label="费用所属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamYear">
              <j-dict-select-tag :disabled="formDisabled" placeholder="请选择费用所属年度" v-model="model.teamYear" dictCode="tdnd_type"/>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
              <select-team-input placeholder="请选择经营团队" :disabled="datailDisabled" v-model="model.teamId" :tdlx="3" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="项目合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectContract">
              <select-contract-manager-input
                showName="1"
                :allList="false"
                :muitFlag="true"
                :disabled="formDisabled"
                v-model="model.projectContract"
                status="2,3,7"
                htlx="1"
                :projectId="model.projectId"
                @back="changeProjectContract" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同款项" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractFund">
              <select-checkoutlist-input :disabled="formDisabled" v-model="model.contractFund" :isFinance="true" :contractNo="model.projectContract" @back="getCheckoutInfo"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="款项金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="itemMoney">
              <a-input-number
                :disabled="datailDisabled"
                :max="99999999"
                :min="0"
                v-model="model.itemMoney"
                placeholder="请输入款项金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="项目进度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectProgress">
              <j-dict-select-tag type="list" :disabled="datailDisabled" placeholder="请选择项目进度" v-model="model.projectProgress" dictCode="erp_progress_contract_node,node_name,id" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-model-item label="预计回款时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimateRefundTime">
              <j-date :disabled="formDisabled" placeholder="请选择预计回款时间" v-model="model.estimateRefundTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="已开票金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="onInvoiceAmount">
              <a-input-number
                :disabled="formDisabled"
                :max="99999999"
                :min="-99999999"
                :precision="2"
                v-model="model.onInvoiceAmount"
                placeholder="请输入已开票金额（元）"
                style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="开票金额（元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceAmount">
              <a-input-number
                :disabled="formDisabled"
                :max="isCancel=='0'?((model.itemMoney==0?0:((model.itemMoney && model.itemMoney!=0) && (model.onInvoiceAmount||model.onInvoiceAmount==0) )?(Number(model.itemMoney-model.onInvoiceAmount)): 99999999)):0"
                :min="isCancel=='0'?0:-99999999"
                :precision="2"
                v-model="model.invoiceAmount"
                placeholder="请输入开票金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="开票类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceCategory">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.invoiceCategory" dictCode="invoice_type" placeholder="请选择开票类型" />
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectNodelistInput from '@/views/scy/components/SelectNodelistInput'
  import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
  import SelectCheckoutlistInput from '@/views/scy/components/SelectCheckoutlistInput'

  export default {
    name: 'ErpFinanceInvoiceExpensesDetailForm',
    components: {
      SelectProjectInput,
      SelectTeamInput,
      SelectUserByDep,
      SelectNodelistInput,
      SelectContractManagerInput,
      SelectCheckoutlistInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      // 签订单位
      sellerUnit: {
        type: String,
        default: null,
        required: false
      },
      // 经营团队
      teamId: {
        type: String,
        default: '',
        required: false
      },
      isCancel: {
        type: String,
        default: '0',
        required: false
      },
    },
    data () {
      return {
        flag: false,
        model: {
          // invoiceCategory: '0',
          projectId: null,
          itemMoney: null,
          invoiceAmount: null
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          projectId: [
              { required: true, message: '请选择项目!', trigger: 'change' }
          ],
          projectContract: [
              { required: true, message: '请选择项目合同!', trigger: 'change' }
          ],
          contractFund: [
              { required: true, message: '请选择合同款项!', trigger: 'change' }
          ],
          projectProgress: [
              { required: true, message: '请输入项目进度!', trigger: 'change' }
          ],
          estimateRefundTime: [
              { required: true, message: '请选择预计回款时间!', trigger: 'change' }
          ],
          invoiceAmount: [
              { required: true, pattern: /^(-([1-9][0-9]*)|([1-9][0-9]*)|-?(0\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/ ,message: '请输入正确的开票金额!', trigger: 'blur' }
          ]
        },
        datailDisabled: true,
        fpList: [], // 主表的发票信息子表
        isAdd: true // 是否点击新增进来的
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      // 合同款项
      getCheckoutInfo(data) {
        console.log('data---->', data)
        this.$refs.form.clearValidate('projectProgress');
        // 款项金额
        this.$set(this.model, 'itemMoney', data[0].paymentMoney);
        // 项目进度
        this.$set(this.model, 'projectProgress', data[0].contractNodeId);
         // 开票金额
         this.$set(this.model, 'onInvoiceAmount', data[0].invoicePaidAmount);
      },
      selectProject(data) {
        const project = data.choseObj[0]
        this.$refs.form.clearValidate('projectContract');
        this.$refs.form.clearValidate('contractFund');
        this.$refs.form.clearValidate('projectProgress');
        if (data && data.choseObj && data.choseObj.length) {
          this.model.projectCode = data.choseObj[0].finalNo
        } else {
          this.model.projectCode = null
        }
        // 经营团队
        this.model.teamId = project.teamName
        // 团队负责人
        this.model.undertaker = project.undertaker
        // 所属年度
        this.model.attributionYear = project.year
        // 项目合同
        this.$set(this.model, 'projectContract', null);
        // 合同款项
        this.$set(this.model, 'contractFund', null);
        // 款项金额
        this.$set(this.model, 'itemMoney', null);
        // 项目进度
        this.$set(this.model, 'projectProgress', null);
      },
      changeProjectContract() {
        // 合同款项
        this.$set(this.model, 'contractFund', null);
        // 款项金额
        this.$set(this.model, 'itemMoney', null);
        // 项目进度
        this.$set(this.model, 'projectProgress', null);
      },
      add () {
        this.edit(this.modelDefault);
        console.log(this.isCancel)
      },
      edit (record) {
        console.log('编辑:', record);
        console.log('编辑:', this.teamId)
        console.log('编辑:', this.sellerUnit)
        this.$refs['form'].clearValidate();
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {
        // 校验是否是同一个项目
        let isChecked = this.checkProjectAdd()
        if (isChecked) {
          const that = this;
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              if (!this.model.id) {
                this.model.id = parseInt(Math.random() * 1000000000000);
              }
              console.log(this.model);
              that.$emit('ok', this.model, this.flag);
            }
          })
        } else {
          // 选择的项目导致子表不是同一个则提示
          // this.$set(this.model,'projectId',null)
          this.$message.warning('所选项目必须为同一个!')
        }
      },
      // 每次点击新增编辑重新加载发票信息子表
      loadList(list) {
        this.fpList = list;
      },
      // 校验本次选择是否合法
      checkProjectAdd() {
        console.log('校验所选项目:', this.model)
        console.log('发票子表:', this.fpList)
        let projectId = this.model.projectId;
        // 值拦截本次选中的项目非法的情况
        if (!!this.fpList && this.fpList.length !== 0) {
          // 是修改且只有一条数据的时候随便选 其他的直接else判断
          if (!this.isAdd && this.fpList.length === 1) {
            return true;
          } else {
            // 本次新增需要项目id相同
            for (let i = 0; i < this.fpList.length; i++) {
              if (this.fpList[i].projectId !== projectId) {
                return false;
              }
            }
          }
        }
        return true;
      }
    }
  }
</script>
